package com.config.channels.service.impl;

import com.config.channels.entity.Channels;
import com.config.channels.repository.ChannelsRepository;
import com.config.channels.service.ChannelsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.nio.channels.Channel;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class ChannelsServiceImpl implements ChannelsService {

    @Autowired
    private ChannelsRepository channelsRepository;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private StringRedisTemplate redisTemplate;
    private String keyPrefix = "channel.";

    @Value("${redirect.error.url}")
    private String errorUrl;

    @Override
    public Channels save(Channels channels) {
        logger.info(String.format("save:id:%s,url:%s",channels.id,channels.url));
        Channels temp = channelsRepository.getByChannelsId(channels.channelsId);
        if(temp != null) {
            channels.id = temp.id;
        }
        return channelsRepository.save(channels);
    }

    @Override
    public Channels getByChannelsId(String id) {
        return channelsRepository.getByChannelsId(id);
    }

    public String getUrl(String id) {
        String key = keyPrefix+id;
        ValueOperations<String, String> ops = this.redisTemplate.opsForValue();
        if(this.redisTemplate.hasKey(key)){
            return ops.get(key);
        } else {
            Channels channel = channelsRepository.getByChannelsId(id);
            if (channel != null) {
                String url = channelsRepository.getByChannelsId(id).url;
                ops.set(key,url,10, TimeUnit.SECONDS);
                System.out.println("get url from mysql" + key + "   " + url);
                return url;

            } else {
                return errorUrl;
            }
        }
    }
}
